/**********
@name: thumb组件
@describtion: 提供缩略图上传策略，可以接收一个图片数组其中选择，还可以在素材库中选择 并且进行裁剪
@author:liubingye
@date:2023-03-09 16:02:45
***********/
<template>
  <div class="thumb-outer-box">
    <div class="editor-icon" v-if="props.children && props.children.length > 0" @click="changeChildrenShow">
      <span :class="{ plus: childrenShow }"></span>
    </div>
    <el-form-item :prop="props.field">
      <div class="thumb-img-box" @click="handleShowThumbBox" :class="'thumb-img-box-' + props.setting.picture_scale">
        <div v-if="thumbImg" class="delete-thumb" @click.stop="deleteThumb">
          <el-icon>
            <Delete />
          </el-icon>
        </div>
        <img v-if="thumbImg" :src="thumbImg" alt />
        <el-icon v-else>
          <Plus />
        </el-icon>
      </div>
    </el-form-item>
    <FilesUpload v-if="showFilesUpload" v-model:showDialog="showFilesUpload" :isPublic="true" @getFileList="insertFiles" :modelId="1" :limit="1" :isToJpg="true"></FilesUpload>
    <el-dialog v-model="showThumbBox" :title="props.title + '选择'" width="944px" class="thumb-tool-box" @close="handleCloseThumbBox" @open="handleOpenThumbBox">
      <div class="image-choose-content">
        <div class="image-choose-step2" v-if="thumbStep === 2">
          <div class="cropper-box">
            <div class="cropper">
              <vueCropper ref="cropper" :img="option.img" :outputSize="option.size" :outputType="option.outputType" :autoCrop="true" :fixed-number="imageScale" :fixed="true" autoCropWidth="10000" autoCropHeight="10000" mode="contain" :full="true" :centerBox="true" :infoTrue="true" @realTime="thumbPreview"></vueCropper>
            </div>
            <div class="cropper-option">
              <el-icon @click="changeScale(1)">
                <ZoomIn />
              </el-icon>
              <el-icon @click="changeScale(-1)">
                <ZoomOut />
              </el-icon>
            </div>
          </div>
          <div class="thumb-preview" v-if="props.setting.picture_scale === 1">
            <p>封面裁剪</p>
            <div class="inner-thumb-preview">
              <div class="thumb-preview-item big-preview">
                <div class="img-box">
                  <div :style="previewStyle">
                    <div :style="previewImg.div">
                      <img :src="previewImg.url" :style="previewImg.img" />
                    </div>
                  </div>
                </div>
                <div class="img-msg">
                  <p>新闻封面（16:9）</p>
                  <span>该内容在列表页中，将显示此类型封面缩略图</span>
                </div>
              </div>
              <div class="thumb-preview-item small-preview">
                <div class="img-box">
                  <div :style="previewStyle" style="transform: translateX(-13%);">
                    <div :style="previewImg.div">
                      <img :src="previewImg.url" :style="previewImg.img" />
                    </div>
                  </div>
                </div>
                <div class="img-msg">
                  <p>新闻封面（4:3）</p>
                  <span>该内容在部分模板中，将显示此类型封面缩略图</span>
                </div>
              </div>
            </div>
          </div>
          <div class="thumb-preview" v-if="props.setting.picture_scale === 2">
            <p>图片裁剪</p>
            <div class="inner-thumb-preview">
              <div class="thumb-preview-item">
                <div class="img-box">
                  <div :style="previewStyle">
                    <div :style="previewImg.div">
                      <img :src="previewImg.url" :style="previewImg.img" />
                    </div>
                  </div>
                </div>
              </div>
              <div class="img-msg">
                <p>图片比例（3:4）</p>
              </div>
            </div>
          </div>
        </div>
        <div class="footer-btn-box">
          <div class="inner-footer">
            <div class="left-btn-box">
              <!-- <el-button round v-if="thumbStep === 2" @click="prevStep">上一步</el-button> -->
            </div>
            <div class="right-btn-box">
              <el-button type="primary" round v-if="thumbStep === 1" :disabled="checkedThumb.length === 0" @click="nextStep" :loading="stepLoading">下一步</el-button>
              <template v-else>
                <el-button type="primary" round @click="uploadThumb">确定</el-button>
                <el-button type title="跳过剪裁，可能会导致前台图片显示偏差" round @click="cropSkip">跳过</el-button>
              </template>
              <el-button round @click="showThumbBox = false">取消</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { reactive, ref, computed } from 'vue'
import { getRandomString, transBase64FromImage } from '@/utils/tools'
import { singleUpload } from '@/utils/upload'
import { Plus, ZoomOut, ZoomIn, Delete } from '@element-plus/icons-vue'
import { useStore } from 'vuex'
import { FilesUpload } from '@ruifox-cms/components'

const store = useStore()
const props = defineProps({
  content: {
    type: String,
    default: '',
  },
  title: {
    type: String,
    default: '',
  },
  value: {
    type: String,
    default: '',
  },
  showForm: {
    type: Boolean,
    default: true,
  },
  field: {
    type: String,
    default: '',
  },
  children: {
    type: Array,
    default: () => [],
  },
  childrenShow: {
    type: Boolean,
    default: false,
  },
  setting: {
    type: Object,
    default: () => {},
  },
})
const singleActionUrl = ref(store.state.base.singleActionUrl)
const emits = defineEmits(['update:value', 'update:childrenShow'])
const childrenShow = computed(() => props.childrenShow)
const changeChildrenShow = () => {
  emits('update:childrenShow', !childrenShow.value)
}
const content = computed(() => {
  return props.content
})

// eslint-disable-next-line vue/return-in-computed-property
const imageScale = computed(() => {
  switch (props.setting.picture_scale) {
    case 1:
      return [16, 9]
    case 2:
      return [3, 4]
  }
})
const handleShowThumbBox = () => {
  thumbList.value = []
  showFilesUpload.value = true
  let tinyCnt = content.value
  let imgList = []
  if (tinyCnt) {
    imgList = tinyCnt.match(/<img[^>]+>/g)
  }
  if (imgList && imgList.length > 0) {
    imgList.forEach((item, index) => {
      item.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
        let imgObj = {
          id: index,
          url: capture,
        }
        thumbList.value.push(imgObj)
      })
    })
    choseThumb.value = [thumbList.value[0]]
    checkedThumb.value = JSON.parse(JSON.stringify(choseThumb.value))
  }
}
const checkedThumb = ref([])
const showThumbBox = ref(false)
const showFilesUpload = ref(false)
const thumbStep = ref(1)
const insertFiles = (filesList) => {
  console.log('filesList', filesList)
  filesList.forEach((item) => {
    if (item.modelId == 1) {
      choseThumb.value = [item]
      checkedThumb.value = [item]
      thumbList.value = [item]
      showThumbBox.value = true
      nextStep()
    }
  })
}

// 正文图片选择
const thumbList = ref([]) //缩略图数组
const choseThumb = ref([])
const imgUploadList = ref([])
const handleCloseThumbBox = () => {
  stepLoading.value = false
  imgUploadList.value = []
  checkedThumb.value = []
  thumbStep.value = 1
}
const handleOpenThumbBox = () => {
  if (thumbImg.value) {
    imgUploadList.value.push({
      url: thumbImg.value,
      percentage: 100,
      status: 'success',
    })
    checkedThumb.value = [
      {
        url: thumbImg.value,
        percentage: 100,
        status: 'success',
      },
    ]
  }
}
const setAvatarBase64 = (src) => {
  return new Promise((resolve) => {
    let image = new Image()
    // 处理缓存
    image.src = src + '?v=' + Math.random()
    // 支持跨域图片
    image.crossOrigin = '*'
    image.onload = () => {
      let base64 = transBase64FromImage(image)
      resolve(base64)
    }
  })
}
const stepLoading = ref(false)
const nextStep = () => {
  stepLoading.value = true
  setAvatarBase64(checkedThumb.value[0].url).then((base64) => {
    thumbStep.value = 2
    stepLoading.value = false
    option.img = base64
  })
}
// const prevStep = () => {
//   thumbStep.value = 1
//   showThumbBox.value = false
//   showFilesUpload.value = true
// }

//缩略图裁剪
const cropper = ref()
const option = reactive({
  img: '',
  size: 1,
  outputType: 'jpg',
})
const previewImg = reactive({
  img: {},
  url: '',
  div: {},
})
const previewStyle = reactive({
  width: '',
  height: '',
  margin: 0,
  zoom: 1,
  overflow: 'hidden',
})
const thumbPreview = (val) => {
  previewImg.img = val.img
  previewImg.url = val.url
  previewImg.div = val.div
  previewStyle.width = val.w + 'px'
  previewStyle.height = val.h + 'px'
  previewStyle.zoom = 90 / val.h
}
const changeScale = (val) => {
  cropper.value.changeScale(val)
}
const thumbImg = computed({
  get: () => {
    return props.value
  },
  set: (val) => {
    emits('update:value', val)
  },
})
const uploadThumb = async () => {
  const { width, height } = cropper.value.cropInfo
  let _fileName = '裁剪图片' + getRandomString(6) + '.jpg'
  cropper.value.getCropBlob(async (blob) => {
    let formData = new FormData()
    // 切割缩略图不分配到资源库，所以不要设置path
    formData.append('name', _fileName)
    formData.append('file', blob)
    formData.append('type', 0)
    formData.append('cropWidth', width)
    formData.append('cropHeight', height)
    formData.append('scaledWidth', width)
    formData.append('scaledHeight', height)
    formData.append('startX', 0)
    formData.append('startY', 0)
    const res = await singleUpload(formData, singleActionUrl.value)
    if (process.env.NODE_ENV === 'development') {
      if (res.data.url.includes('192.168.2.150')) {
        res.data.url = res.data.url.replace('192.168.2.150', '10.10.0.19')
      }
    }
    thumbImg.value = res.data.url
    showThumbBox.value = false
    handleCloseThumbBox()
  })
}
// 跳过
const cropSkip = () => {
  thumbImg.value = imgUploadList.value[0].url
  showThumbBox.value = false
}
const deleteThumb = () => {
  thumbImg.value = ''
}
// 暴露方法
defineExpose({
  handleShowThumbBox,
  deleteThumb,
})
</script>
<style scoped lang="scss">
.thumb-img-box {
  border: 1px solid #c4c9d5;
  height: 120px;
  width: 176px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #ffffff;
  transition: all 0.3s;
  position: relative;
  margin: 40px 30px 0 0;

  i.no-thumb {
    font-size: 36px;
    color: #aaaaaa;
  }

  img {
    width: 100%;
    height: 100%;
    max-height: 100%;
    max-width: 100%;
  }

  .delete-thumb {
    color: $white;
    position: absolute;
    right: 0;
    top: 0;
    cursor: pointer;
    display: none;
    height: 24px;
    width: 24px;
    background-color: #ff5240;
    box-sizing: border-box;
    border: 1px solid rgba(255, 255, 255, 0.5);
    align-items: center;
    justify-content: center;

    i {
      font-size: 16px;
    }
  }

  &:hover {
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);

    .delete-thumb {
      display: flex;
    }
  }
}

.thumb-img-box.thumb-img-box-2 {
  height: 120px;
  width: 90px;
}

::v-deep(.thumb-tool-box .el-dialog__body) {
  padding: 0;
}

.thumb-tool-box {
  .image-choose-content {
    .uploader-content {
      .upload-img-box {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        min-height: 300px;

        & > div {
          height: 160px;
          width: 160px;
          margin-right: 20px;
          margin-top: 20px;
          background-color: #f8f8f8;
        }

        & > div:nth-child(5n + 1) {
          margin-left: 18px;
        }

        li {
          transition: all 0.3s;
          height: 160px;
          width: 160px;
          box-sizing: border-box;
          list-style: none;
          border: 1px solid #e4e4e4;
          display: flex;
          align-items: center;
          justify-content: center;
          position: relative;
          cursor: pointer;

          .img-box {
            height: 158px;
            width: 158px;
            display: flex;
            justify-content: center;
            align-items: center;

            img {
              max-width: 158px;
              max-height: 158px;
            }
          }

          .progress-box {
            width: 100%;
            position: absolute;
            bottom: 0;

            ::v-deep(.el-progress-bar__outer) {
              border-radius: 0;
            }

            ::v-deep(.el-progress-bar__inner) {
              border-radius: 0;
            }
          }

          .remove-upload {
            color: $white;
            position: absolute;
            right: 5px;
            top: 5px;
            cursor: pointer;
            display: none;
            height: 24px;
            width: 24px;
            background-color: #ff5240;
            box-sizing: border-box;
            border: 1px solid rgba(255, 255, 255, 0.5);
            align-items: center;
            justify-content: center;

            i {
              font-size: 16px;
            }
          }

          &:hover {
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
            border-color: $mainColor;
            background-color: $focusContent;

            .remove-upload {
              display: flex;
            }
          }
        }
      }
    }

    .inner-image-choose {
      padding: 0 20px;

      .material-choose-box {
        display: flex;
        margin-bottom: 10px;

        .btn {
          padding: 0 15px;
          line-height: 32px;
          height: 32px;
          border-radius: 100px;
          margin-right: 10px;
          cursor: pointer;
          border: 1px solid #c4c9d5;
        }

        .btn.is-active {
          background-color: $mainColor;
          border-color: $mainColor;
          color: $white;
        }
      }
    }

    h3 {
      font-size: 14px;
      font-weight: normal;
      padding: 10px 0;
    }

    ::v-deep(.el-tabs__item.is-top:nth-child(2)) {
      padding-left: 20px;
    }

    .image-choose-step1 {
      .thumb-list-box {
        display: flex;
        flex-wrap: wrap;

        .thumb-item {
          position: relative;
          height: 160px;
          width: 160px;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #f0f2f7;
          margin-right: 15px;
          margin-bottom: 15px;
          box-sizing: border-box;
          cursor: pointer;

          .thumb-item-checkbox {
            position: absolute;
            left: 5px;
            top: 0;
          }

          &.checked {
            border: 1px solid $mainColor;
          }

          &:nth-child(5n) {
            margin-right: 0;
          }

          img {
            max-height: 100%;
            max-width: 100%;
          }
        }
      }
    }

    .image-choose-step2 {
      display: flex;
      padding-top: 24px;
      justify-content: space-between;

      .cropper-box {
        width: 468px;

        .cropper {
          width: 100%;
          height: 430px;
        }

        .cropper-option {
          height: 40px;
          width: 100%;
          border-top: 1px solid #dcdfe6;
          background-color: $backBase;
          display: flex;
          justify-content: center;
          align-items: center;

          .el-icon {
            cursor: pointer;
            font-size: 24px;
          }

          .el-icon:nth-child(1) {
            margin-right: 20px;
          }
        }
      }

      .thumb-preview {
        width: 374px;

        .inner-thumb-preview {
          .thumb-preview-item.big-preview {
            margin-top: 24px;

            .img-box {
              height: 90px;
              width: 160px;
              overflow: hidden;
            }
          }

          .thumb-preview-item.small-preview {
            margin-top: 30px;

            .img-box {
              height: 90px;
              width: 120px;
              overflow: hidden;
            }
          }

          .thumb-preview-item {
            display: flex;
            justify-content: space-between;

            .img-box img {
              max-width: none;
            }

            .img-msg {
              width: 210px;

              p {
                font-size: 14px;
                margin-bottom: 10px;
              }

              span {
                @include tipsText();
              }
            }
          }
        }
      }
    }

    .footer-btn-box {
      padding: 30px 20px;

      .inner-footer {
        display: flex;
        justify-content: space-between;
      }
    }
  }
}

.no-upload-list {
  i {
    color: $mainColor;
  }
}
</style>
